package com.lkd.utils;

import com.lkd.config.MinioConfig;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class MinioUtil {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioConfig minioConfig;

    public String upload(String fileName, Long size, String contentType, InputStream inputStream){

        String bucket = minioConfig.getBucket();
        String endpoint = minioConfig.getEndpoint();

        String url = "";
        try {
            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            }

            //设置文件最终的路径和名称
            String objectName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                    + "/" + System.currentTimeMillis() +"-"+fileName;

            // 通过流上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucket).object(objectName).stream(
                            inputStream, size, -1)
                            .contentType(contentType)
                            .build());

            url = endpoint+"/"+bucket+"/"+objectName;
            System.out.println("上传完成，资源访问地址："+url);

        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                }catch (IOException e){
                    log.error("上传文件流关闭异常：{}",e.getMessage());
                }
            }
        }
        //返回上传之后的url
        return url;
    }

}